package edu.lit.wantwords.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import edu.lit.wantwords.entity.Users;
import edu.lit.wantwords.entity.Words;
import edu.lit.wantwords.service.UsersService;
import edu.lit.wantwords.service.WordsService;
import edu.lit.wantwords.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yc
 * @since 2022-06-24
 */
@Api(description = "用户操作")
@RestController
@RequestMapping("/word/users")
@CrossOrigin
public class UsersController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private WordsService wordsService;

    @ApiOperation(value = "用户登录")
    @PostMapping("login")
    public R login(@RequestBody Users user) {
        Users users = usersService.getOne(new LambdaQueryWrapper<Users>()
                .eq(Users::getUserName, user.getUserName())
                .eq(Users::getPassword, user.getPassword()));
        if ( users == null ) return R.error();
        return R.ok();
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("register")
    public R register(@RequestBody Users users) {
        Users one = usersService.getOne(new LambdaQueryWrapper<Users>()
                .eq(Users::getUserName, users.getUserName()));
        if ( one != null ) {
            return R.error();
        }
        boolean save = usersService.save(users);
        if ( save ) return R.ok();
        return R.error();
    }

    @ApiOperation(value = "根据用户名获取用户信息")
    @GetMapping("getByUserName/{userName}")
    public R getByUserName(@PathVariable String userName) {
        Users users = this.getUsers(userName);
        return R.ok().data("user", users);
    }

    @ApiOperation(value = "删除搜索历史")
    @DeleteMapping("delAllSearchHistory/{userName}")
    public R delAllSearchHistory(@PathVariable String userName) {
        Users users = this.getUsers(userName);
        users.setUserSearchHistory(null);
        boolean update = usersService.update(users, new UpdateWrapper<Users>()
                .set("user_search_history", null)
                .eq("user_name", userName));
        if ( update ) return R.ok();
        return R.error();
    }

    @ApiOperation(value = "获取用户搜索历史")
    @GetMapping("getSearchHistoryByUserName/{userName}")
    public R getSearchHistoryByUserName(@PathVariable String userName) {
        Users users = this.getUsers(userName);
        if ( users.getUserSearchHistory() == null ) {
            return R.ok().data("history", "null");
        }
        String userSearchHistory = users.getUserSearchHistory();
        List<Words> list = JSONArray.parseArray(userSearchHistory, Words.class);
        return R.ok().data("history", list);
    }

    @ApiOperation(value = "添加搜索历史")
    @PostMapping("addSearchHistory/{userName}")
    public R addSearchHistory(@RequestBody Words word,
                              @PathVariable String userName) {
        if ( wordsService.getOne(new LambdaQueryWrapper<Words>()
        .eq(Words::getWord, word.getWord())) == null ) {
            return R.error();
        } else {
            String words = JSON.toJSONString(word);
            Users users = this.getUsers(userName);
            String userSearchHistory = users.getUserSearchHistory();
            if ( userSearchHistory == null ) {
                users.setUserSearchHistory("[" + words + "]");
            } else {
                StringBuilder stringBuilder = new StringBuilder(userSearchHistory);
                stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("]"));
                stringBuilder.append("," + words + "]");
                userSearchHistory = stringBuilder.toString();
                users.setUserSearchHistory(userSearchHistory);
            }
            boolean b = usersService.updateById(users);
            if ( b ) return R.ok();
            return R.error();
        }
    }

    @ApiOperation(value = "添加生词本")
    @PostMapping("addRowWord/{userName}")
    public R addRowWord(@RequestBody Words word,
                        @PathVariable String userName) {
        String words = JSON.toJSONString(word);
        Users users = this.getUsers(userName);
        String userSearchHistory = users.getUserRow();
        if ( userSearchHistory != null ) {
            List<Words> list = JSONArray.parseArray(userSearchHistory, Words.class);
            for (Words words1 : list) {
                if ( words1.getWord().equals(word.getWord()) ) {
                    return R.error().data("have", "该单词已加入生词本");
                }
            }
        }
        if ( userSearchHistory == null ) {
            users.setUserRow("[" + words + "]");
        } else {
            StringBuilder stringBuilder = new StringBuilder(userSearchHistory);
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("]"));
            stringBuilder.append("," + words + "]");
            userSearchHistory = stringBuilder.toString();
            users.setUserRow(userSearchHistory);
        }
        boolean b = usersService.updateById(users);
        if ( b ) return R.ok();
        return R.error();
    }

    @ApiOperation(value = "更新已经背到了第几个单词")
    @GetMapping("updateCurrentNum/{userName}")
    public R updateCurrentNum(@PathVariable String userName) {
        Users users = this.getUsers(userName);
        if ( users.getUserFinishedNum() == null ) {
            users.setUserFinishedNum(20);
        } else {
            users.setUserFinishedNum(users.getUserFinishedNum() + 20);
        }
        boolean b = usersService.updateById(users);
        if ( b ) return R.ok();
        return R.error();
    }

    @ApiOperation(value = "已经背了多少单词")
    @GetMapping("getHaveFinishedWordsNum/{userName}")
    public R getHaveFinishedWordsNum(@PathVariable String userName) {
        Users users = this.getUsers(userName);
        return R.ok().data("userFinishedNum", users.getUserFinishedNum());
    }

    @ApiOperation(value = "获取用户生词本")
    @GetMapping("getRowBook/{userName}")
    public R getRowBook(@PathVariable String userName) {
        Users users = this.getUsers(userName);
        List<Words> list = JSONArray.parseArray(users.getUserRow(), Words.class);
        return R.ok().data("list", list);
    }

    @ApiOperation(value = "从生词本中删除")
    @DeleteMapping("removeFromRow/{userName}/{word}")
    public R removeFromRow(@PathVariable String userName,
                           @PathVariable String word) {
        Users users = this.getUsers(userName);
        String userSearchHistory = users.getUserRow();
        List<Words> list = JSONArray.parseArray(userSearchHistory, Words.class);
        for (int i = 0; i < list.size(); i++) {
            if ( list.get(i).getWord().equals(word) ) {
                list.remove(i);
            }
        }
        String string = JSON.toJSONString(list);
        users.setUserRow(string);
        boolean b = usersService.updateById(users);
        if ( b ) return R.ok();
        return R.error();
    }

    @ApiOperation(value = "随机选取20个单词")
    @GetMapping("getWordList")
    public R getWordList() {
        int i = new Random().nextInt(5184);
        List<Words> wordsList = wordsService.list(new LambdaQueryWrapper<Words>()
        .between(Words::getSortNum, i, i + 19));
        return R.ok().data("wordsList", wordsList);
    }

    @ApiOperation(value = "修改密码")
    @PutMapping("changePassword/{userName}/{password}")
    public R changePassword(@PathVariable String userName,
                            @PathVariable String password) {
        Users users = this.getUsers(userName);
        users.setPassword(password);
        boolean b = usersService.updateById(users);
        if ( b ) return R.ok();
        return R.error();
    }


    //根据userName获取用户
    public Users getUsers(String userName) {
        Users users = usersService.getOne(new LambdaQueryWrapper<Users>()
                .eq(Users::getUserName, userName));
        return users;
    }

    //将对象转换为json
    public String objToJson(T t, String str) {
        String words = JSON.toJSONString(t);
        if ( str == null ) {
            str = "[" + words + "]";
        } else {
            StringBuilder stringBuilder = new StringBuilder(str);
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("]"));
            stringBuilder.append("," + words + "]");
            str = stringBuilder.toString();
        }
        return str;
    }
}

